import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';

const APPBAR_SCROLL_OFFSET = 100;

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  double _appBarAlpha = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget>[
          _mainContent(context),
          _customAppBar,
        ],
      ),
    );
  }

  // 自定义appbar
  Widget get _customAppBar {
    return Opacity(
      opacity: _appBarAlpha,
      child: Container(
        height: 80,
        decoration: BoxDecoration(color: Colors.white),
        child: Text('data'),
      ),
    );
  }

  // 主要内容
  Widget _mainContent(BuildContext context) {
    return MediaQuery.removePadding(
      removeTop: true,
      context: context,
      child: NotificationListener(
        onNotification: (ScrollNotification scrollNotification) {
          if (scrollNotification is ScrollUpdateNotification &&
              scrollNotification.depth == 0) {
            // 滚动且是列表滚动的时候
            _onPageScroll(scrollNotification.metrics.pixels);
          }
        },
        child: ListView(
          children: <Widget>[
            _swiperWidget,
          ],
        ),
      ),
    );
  }

  // 轮播图
  Widget get _swiperWidget {
    return Container(
      height: 160,
      child: Swiper(
        itemCount: 3,
        autoplay: true,
        pagination: SwiperCustomPagination(
            builder: (BuildContext context, SwiperPluginConfig config) {
          // return new Pagina;
        }),
        itemHeight: 160,
        itemBuilder: (BuildContext context, int index) {
          return Container(
            child: InkWell(
              onTap: () {},
              child: Image.network(
                '',
                fit: BoxFit.fill,
              ),
            ),
          );
        },
      ),
    );
  }

  void _onPageScroll(double offset) {
    double alpha = offset / APPBAR_SCROLL_OFFSET;
    if (alpha < 0) {
      alpha = 0;
    } else if (alpha > 1) {
      alpha = 1;
    }

    setState(() {
      _appBarAlpha = alpha;
    });
  }
}
